from sqlalchemy.sql import text
from sqlalchemy import insert, select

from model.user import User
from x_com import xport_core
logger = xport_core.getLogger()


# # 创建表
# async def create_table():
#     async with SERVICE.engine.connect() as conn:
#          # 查询数据中是否已经存在表 user
#         result = await conn.execute(text("SELECT name FROM sqlite_master WHERE type='table' AND name='user'"))
#         table_exist = result.fetchone()
#         if not table_exist:
#             create_user_class(SERVICE.Base)
#             # 表不存在，使用异步方式创建表
#             # 使用同步创建表
#             await conn.run_sync(lambda sync_conn: SERVICE.Base.metadata.create_all(sync_conn))

# 通过 name 查看结果
async def find_by_name(conn, name):
    # User = create_user_class(SERVICE.Base)
    query = select(User).filter(User.name == name)
    result = await conn.execute(query)
    user = result.fetchone()
    return user

# 添加用户
async def add_user(conn, username, password, salt):
    # User = create_user_class(SERVICE.Base)
    query = insert(User).values(
        name=username, password=password, salt=salt)
    await conn.execute(query)
